<template>
  <div class="car-list-page">
    <div class="container">
      <!-- 双11特惠横幅 -->
      <div class="promotion-banner">
        <div class="banner-content">
          <div class="banner-text">
            <h2 class="banner-title">双11特惠：全场车源直降 5000 元</h2>
            <p class="banner-subtitle">活动时间：11.1-11.11</p>
          </div>
          <el-button 
            class="banner-btn" 
            size="medium"
            @click="showPromotionDialog"
          >
            了解活动详情
          </el-button>
        </div>
      </div>
      
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-card class="filter-card">
          <div class="filter-row">
            <div class="filter-group">
              <span class="filter-label">品牌:</span>
              <el-select 
                v-model="filters.brand" 
                placeholder="选择品牌" 
                clearable
                @change="handleFilterChange"
              >
                <el-option
                  v-for="brand in brandOptions"
                  :key="brand.value"
                  :label="brand.label"
                  :value="brand.value"
                />
              </el-select>
            </div>
            
            <div class="filter-group">
              <span class="filter-label">价格:</span>
              <el-select 
                v-model="filters.priceRange" 
                placeholder="选择价格" 
                clearable
                @change="handleFilterChange"
              >
                <el-option
                  v-for="price in priceOptions"
                  :key="price.value"
                  :label="price.label"
                  :value="price.value"
                />
              </el-select>
            </div>
            
            <div class="filter-group">
              <span class="filter-label">车龄:</span>
              <el-select 
                v-model="filters.age" 
                placeholder="选择车龄" 
                clearable
                @change="handleFilterChange"
              >
                <el-option
                  v-for="age in ageOptions"
                  :key="age.value"
                  :label="age.label"
                  :value="age.value"
                />
              </el-select>
            </div>
            
            <div class="filter-group">
              <span class="filter-label">里程:</span>
              <el-select 
                v-model="filters.distance" 
                placeholder="选择里程" 
                clearable
                @change="handleFilterChange"
              >
                <el-option
                  v-for="distance in distanceOptions"
                  :key="distance.value"
                  :label="distance.label"
                  :value="distance.value"
                />
              </el-select>
            </div>
          </div>
          
          <!-- 已选条件显示 -->
          <div v-if="hasActiveFilters" class="active-filters">
            <div class="active-filters-label">已选条件:</div>
            <div class="filter-tags">
              <el-tag
                v-for="filter in activeFilterTags"
                :key="filter.key"
                closable
                @close="removeFilter(filter.key)"
              >
                {{ filter.label }}
              </el-tag>
            </div>
          </div>
          
          <div class="filter-row">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </el-card>
      </div>

      <!-- 排序和视图 -->
      <div class="toolbar">
        <div class="sort-options">
          <el-radio-group v-model="sortBy" @change="handleSortChange">
            <el-radio-button label="default">默认</el-radio-button>
            <el-radio-button label="price_asc">价格从低到高</el-radio-button>
            <el-radio-button label="price_desc">价格从高到低</el-radio-button>
            <el-radio-button label="distance_asc">里程从少到多</el-radio-button>
            <el-radio-button label="distance_desc">里程从多到少</el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="view-toggle">
          <el-button-group>
            <el-button 
              :type="viewMode === 'grid' ? 'primary' : ''" 
              @click="viewMode = 'grid'"
            >
              <el-icon><Grid /></el-icon>
            </el-button>
            <el-button 
              :type="viewMode === 'list' ? 'primary' : ''" 
              @click="viewMode = 'list'"
            >
              <el-icon><List /></el-icon>
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 车辆列表 -->
      <div class="car-list">
        <template v-if="carStore.loading">
          <div class="loading-container">
            <el-skeleton :rows="6" animated />
          </div>
        </template>
        
        <template v-else>
          <div v-if="filteredCars.length === 0" class="empty-state">
            <el-empty :description="emptyDescription" />
          </div>
          
          <div v-else :class="['car-container', viewMode]">
            <el-card
              v-for="car in paginatedCars"
              :key="car.id"
              class="car-item"
              shadow="hover"
              @click="$router.push(`/car/${car.id}`)"
            >
              <div class="car-image">
                <img 
                  :src="getCarImage(car)" 
                  :alt="car.title"
                  @error="(e) => handleImageError(e, car)"
                >
                <div class="car-tags">
                  <el-tag v-if="car.is_new" type="success" size="small">准新车</el-tag>
                  <el-tag v-if="car.hot" type="danger" size="small">热门</el-tag>
                </div>
              </div>
              
              <div class="car-content">
                <h3 class="car-title">{{ car.title }}</h3>
                <p class="car-desc">{{ car.subtitle || car.description }}</p>
                
                <div class="car-meta">
                  <div class="meta-item">
                    <el-icon><Odometer /></el-icon>
                    <span>{{ car.distance }}万公里</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatRegDate(car.reg_date) }}上牌</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ car.location }}</span>
                  </div>
                </div>
                
                <div class="car-price">
                  <span class="price">{{ car.price }}万</span>
                  <span class="original-price" v-if="car.original_price">
                    新车{{ car.original_price }}万
                  </span>
                </div>
                
                <div class="car-actions">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click.stop="handleContact(car)"
                  >
                    联系卖家
                  </el-button>
                  <el-button 
                    :type="isFavorite(car.id) ? 'danger' : 'default'" 
                    size="small"
                    :icon="Star"
                    @click.stop="handleFavorite(car.id)"
                  >
                    {{ isFavorite(car.id) ? '已收藏' : '收藏' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </template>
      </div>

      <!-- 活动规则弹窗 -->
      <el-dialog
        v-model="promotionDialogVisible"
        title="双11特惠活动规则"
        width="500px"
        center
      >
        <div class="promotion-dialog-content">
          <h3>活动详情</h3>
          <ul>
            <li>活动期间所有车源价格直降5000元</li>
            <li>活动时间：11月1日-11月11日</li>
            <li>活动覆盖所有品牌和车型</li>
            <li>此优惠不可与其他优惠同时使用</li>
            <li>活动最终解释权归平台所有</li>
          </ul>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="promotionDialogVisible = false">
              我知道了
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分页 -->
      <div class="pagination" v-if="filteredCars.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="filteredCars.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Grid, List, Odometer, Calendar, Location, Star } from '@element-plus/icons-vue'
import { useCarStore } from '@/store/car'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const carStore = useCarStore()
const userStore = useUserStore()

const viewMode = ref('grid')
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(12) // 增加每页显示数量
const promotionDialogVisible = ref(false)

// 筛选条件
const filters = reactive({
  brand: '',
  priceRange: '',
  age: '',
  distance: ''
})

const brandOptions = [
  { label: '大众', value: 'volkswagen' },
  { label: '丰田', value: 'toyota' },
  { label: '本田', value: 'honda' },
  { label: '奔驰', value: 'benz' },
  { label: '宝马', value: 'bmw' },
  { label: '奥迪', value: 'audi' }
]

const priceOptions = [
  { label: '5万以下', value: '0-5' },
  { label: '5-10万', value: '5-10' },
  { label: '10-15万', value: '10-15' },
  { label: '15-20万', value: '15-20' },
  { label: '20万以上', value: '20-' }
]

const ageOptions = [
  { label: '1年以内', value: '1' },
  { label: '1-3年', value: '1-3' },
  { label: '3-5年', value: '3-5' },
  { label: '5年以上', value: '5' }
]

const distanceOptions = [
  { label: '3万公里内', value: '0-3' },
  { label: '3-6万公里', value: '3-6' },
  { label: '6-10万公里', value: '6-10' },
  { label: '10万公里以上', value: '10' }
]

// 计算属性
const hasActiveFilters = computed(() => {
  return Object.values(filters).some(value => value !== '')
})

const activeFilterTags = computed(() => {
  const tags = []
  
  if (filters.brand) {
    const brand = brandOptions.find(b => b.value === filters.brand)
    if (brand) {
      tags.push({ key: 'brand', label: `品牌: ${brand.label}` })
    }
  }
  
  if (filters.priceRange) {
    const price = priceOptions.find(p => p.value === filters.priceRange)
    if (price) {
      tags.push({ key: 'priceRange', label: `价格: ${price.label}` })
    }
  }
  
  if (filters.age) {
    const age = ageOptions.find(a => a.value === filters.age)
    if (age) {
      tags.push({ key: 'age', label: `车龄: ${age.label}` })
    }
  }
  
  if (filters.distance) {
    const distance = distanceOptions.find(d => d.value === filters.distance)
    if (distance) {
      tags.push({ key: 'distance', label: `里程: ${distance.label}` })
    }
  }
  
  return tags
})

const emptyDescription = computed(() => {
  if (hasActiveFilters.value) {
    return '没有找到符合条件的车辆，请尝试调整筛选条件'
  }
  return '暂无车辆数据'
})

// 筛选后的车辆列表
const filteredCars = computed(() => {
  let cars = [...carStore.carList]
  
  console.log('总车辆数:', cars.length)
  console.log('所有车辆:', cars.map(car => ({ id: car.id, title: car.title })))
  
  // 品牌筛选
  if (filters.brand) {
    cars = cars.filter(car => car.brand === filters.brand)
  }
  
  // 价格筛选
  if (filters.priceRange) {
    const [minPrice, maxPrice] = filters.priceRange.split('-').map(Number)
    cars = cars.filter(car => {
      const price = car.price
      if (filters.priceRange === '20-') {
        return price >= 20
      } else if (maxPrice) {
        return price >= minPrice && price <= maxPrice
      } else {
        return price >= minPrice
      }
    })
  }
  
  // 车龄筛选
  if (filters.age) {
    const currentYear = new Date().getFullYear()
    cars = cars.filter(car => {
      if (!car.reg_date) return false
      
      const regYear = new Date(car.reg_date).getFullYear()
      const age = currentYear - regYear
      
      if (filters.age === '1') {
        return age <= 1
      } else if (filters.age === '5') {
        return age >= 5
      } else {
        const [minAge, maxAge] = filters.age.split('-').map(Number)
        return age >= minAge && age <= maxAge
      }
    })
  }
  
  // 里程筛选
  if (filters.distance) {
    cars = cars.filter(car => {
      const distance = car.distance
      if (filters.distance === '10') {
        return distance >= 10
      } else {
        const [minDistance, maxDistance] = filters.distance.split('-').map(Number)
        return distance >= minDistance && distance <= maxDistance
      }
    })
  }
  
  // 排序
  if (sortBy.value !== 'default') {
    cars.sort((a, b) => {
      switch (sortBy.value) {
        case 'price_asc':
          return a.price - b.price
        case 'price_desc':
          return b.price - a.price
        case 'distance_asc':
          return a.distance - b.distance
        case 'distance_desc':
          return b.distance - a.distance
        default:
          return 0
      }
    })
  }
  
  console.log('筛选后车辆数:', cars.length)
  return cars
})

// 分页后的车辆列表
const paginatedCars = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCars.value.slice(start, end)
})

// 显示活动详情弹窗
const showPromotionDialog = () => {
  promotionDialogVisible.value = true
}

// 获取车辆图片
const getCarImage = (car) => {
  // 优先使用处理过的 images 数组
  if (car.images && car.images.length > 0) {
    const firstImage = car.images[0]
    return firstImage
  }
  
  // 其次使用 main_image（需要处理路径）
  if (car.main_image) {
    const processedImage = processImagePath(car.main_image)
    return processedImage
  }
  
  // 最后使用默认图片
  return '/images/default-car.png'
}

const processImagePath = (imagePath) => {
  if (!imagePath) return '/images/default-car.png'
  
  // 如果已经是完整路径，直接返回
  if (imagePath.startsWith('http') || imagePath.startsWith('/')) {
    return imagePath
  }
  
  // 对于简单的文件名，构建正确路径
  return `/images/cars/${imagePath}`
}

// 格式化上牌日期
const formatRegDate = (regDate) => {
  if (!regDate) return ''
  // 如果是 Date 对象
  if (regDate instanceof Date) {
    return regDate.toISOString().split('T')[0].replace(/-/g, '-')
  }
  // 如果是字符串
  if (typeof regDate === 'string') {
    return regDate.split('T')[0]
  }
  return regDate
}

const isFavorite = computed(() => (carId) => {
  return carStore.favorites.some(fav => fav.id === carId)
})

// 图片加载错误处理
const handleImageError = (e, car) => {
  // 立即使用默认图片
  e.target.src = '/images/default-car.png'
  e.target.alt = '图片加载失败'
}

// 筛选条件变化处理
const handleFilterChange = () => {
  currentPage.value = 1
  // 这里可以添加API调用，如果需要后端筛选的话
  // 目前使用前端筛选，所以不需要额外调用
}

const handleSearch = () => {
  currentPage.value = 1
  // 触发重新计算筛选结果
}

const handleReset = () => {
  Object.keys(filters).forEach(key => {
    filters[key] = ''
  })
  currentPage.value = 1
  sortBy.value = 'default'
}

// 移除单个筛选条件
const removeFilter = (filterKey) => {
  filters[filterKey] = ''
  currentPage.value = 1
}

const handleSortChange = () => {
  // 排序已经在计算属性中处理
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const handleContact = (car) => {
  ElMessage.success(`联系卖家: ${car.seller?.phone || '400-123-4567'}`)
}

const handleFavorite = async (carId) => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }

  try {
    if (isFavorite.value(carId)) {
      await carStore.removeFavorite(carId)
      ElMessage.success('取消收藏成功')
    } else {
      await carStore.addFavorite(carId)
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const fetchCars = async () => {
  try {
    // 获取所有车辆，不限制数量
    await carStore.fetchCarList({ limit: 1000 }) // 设置一个足够大的limit
    console.log('获取到的车辆数据:', carStore.carList)
  } catch (error) {
    console.error('获取车辆列表失败:', error)
    ElMessage.error('获取车辆列表失败')
  }
}

onMounted(() => {
  // 初始化时从URL参数设置筛选条件
  if (route.query.brand) {
    filters.brand = route.query.brand
  }
  fetchCars()
})

// 监听车辆列表变化，重置分页
watch(() => carStore.carList, () => {
  currentPage.value = 1
  console.log('车辆列表更新，总数:', carStore.carList.length)
})
</script>

<style lang="scss" scoped>
.car-list-page {
  padding: 20px 0;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

// 双11特惠横幅样式
.promotion-banner {
  background: linear-gradient(135deg, #fff9f2 0%, #fff0e6 100%);
  border: 1px solid #ffe4cc;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 16px 24px;
  box-shadow: 0 2px 8px rgba(255, 122, 0, 0.08);

  .banner-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .banner-text {
      text-align: center;
      flex: 1;
      
      .banner-title {
        color: #FF7A00;
        font-weight: 600;
        font-size: 22px;
        margin: 0 0 4px 0;
        line-height: 1.3;
      }
      
      .banner-subtitle {
        color: #666666;
        font-weight: 400;
        font-size: 14px;
        margin: 0;
      }
    }
    
    .banner-btn {
      border: 1px solid #FF7A00;
      color: #FF7A00;
      background-color: #fff;
      padding: 8px 16px;
      transition: all 0.3s;
      
      &:hover {
        background-color: #fff7f0;
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(255, 122, 0, 0.15);
      }
    }
  }
}

// 活动规则弹窗样式
.promotion-dialog-content {
  h3 {
    color: #333;
    margin-bottom: 16px;
  }
  
  ul {
    padding-left: 20px;
    
    li {
      margin-bottom: 8px;
      color: #666;
      line-height: 1.5;
    }
  }
}

.filter-section {
  margin-bottom: 20px;

  .filter-card {
    .filter-row {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .filter-group {
      display: flex;
      align-items: center;
      gap: 10px;

      .filter-label {
        font-weight: 500;
        color: #333;
        white-space: nowrap;
      }
    }

    // 已选条件样式
    .active-filters {
      margin: 15px 0;
      padding: 12px 0;
      border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;

      .active-filters-label {
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
      }

      .filter-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .el-tag {
          background-color: #f0f7ff;
          border-color: #409eff;
          color: #409eff;
        }
      }
    }
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.car-list {
  min-height: 400px;
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  padding: 60px 0;
}

.car-container {
  &.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
  }

  &.list {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .car-item {
      display: flex;
      gap: 20px;

      .car-image {
        width: 200px;
        height: 150px;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .car-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }
    }
  }
}

.car-item {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .car-image {
    position: relative;
    height: 200px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
    }

    .car-tags {
      position: absolute;
      top: 10px;
      left: 10px;
      display: flex;
      gap: 5px;
    }
  }

  .car-content {
    padding: 15px;

    .car-title {
      margin: 0 0 8px;
      font-size: 16px;
      color: #333;
      line-height: 1.4;
    }

    .car-desc {
      margin: 0 0 12px;
      color: #666;
      font-size: 14px;
      line-height: 1.5;
    }

    .car-meta {
      display: flex;
      gap: 15px;
      margin-bottom: 12px;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: #999;

        .el-icon {
          font-size: 14px;
        }
      }
    }

    .car-price {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .price {
        font-size: 20px;
        font-weight: bold;
        color: #ff6a00;
      }

      .original-price {
        font-size: 12px;
        color: #999;
        text-decoration: line-through;
      }
    }

    .car-actions {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
}

// 筛选器选中状态增强
:deep(.el-select .el-input.is-focus .el-input__inner) {
  border-color: #ff6a00;
}

:deep(.el-select-dropdown__item.selected) {
  color: #ff6a00;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #ff6a00;
  border-color: #ff6a00;
}

@media (max-width: 768px) {
  .filter-section {
    .filter-card {
      .filter-row {
        flex-direction: column;
        gap: 15px;
      }

      .filter-group {
        width: 100%;
        justify-content: space-between;
      }
    }
  }
  
  .promotion-banner {
    padding: 12px 16px;
    
    .banner-content {
      flex-direction: column;
      gap: 12px;
      
      .banner-text {
        .banner-title {
          font-size: 18px;
        }
      }
    }
  }

  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .car-container {
    &.grid {
      grid-template-columns: 1fr;
    }

    &.list {
      .car-item {
        flex-direction: column;

        .car-image {
          width: 100%;
          height: 200px;
        }
      }
    }
  }
}
</style>